from fastapiApp.models.agvs import *
from fastapiApp.schemas.agvs_scheams import *
from fastapi.exceptions import HTTPException
from fastapiApp.models.map import Map_Node_Mo

class AGVcarController(AGV_car_Mo):
    def __init__(self):
        self.model = AGV_car_Mo

    # 判断 能否添加
    async def is_exist(self, obj_in : AGVcarCreate) -> int:
        if await self.model.filter(agv_index=obj_in.agv_index).exists():
            raise HTTPException(status_code=401, detail="AGV编号已存在")
        if await self.model.filter(remote_host=obj_in.remote_host,remote_port=obj_in.remote_port).exists():
            raise HTTPException(status_code=401, detail="IP地址和端口冲突")
        return 0

    # 查看agv car配置list
    async def list(self, page: int, page_size: int):
        query = await self.model.filter().offset((page - 1) * page_size).limit(page_size)
        count = await self.model.filter().count()
        data_list = [
            await role.to_dict()
            for role in query
        ]
        return count,data_list

    # 更新agv car配置
    async def update_agv_car(self, obj_in:AGVcarUpdate) -> None:
        agv = await self.model.get(id=obj_in.id)
        agv.agv_index = obj_in.agv_index
        agv.remote_host = obj_in.remote_host
        agv.remote_port = obj_in.remote_port
        agv.local_port = obj_in.local_port
        agv.timeout = obj_in.timeout
        agv.timesend = obj_in.timesend
        await agv.save()


class AGVPositionController(AGV_position_Mo):
    def __init__(self):
        self.model = AGV_position_Mo

    # 查看实时位置
    async def get_all_position(self):
        # 使用prefetch_related预加载关联的站点信息，减少数据库查询次数
        query = await self.model.all().prefetch_related('node_to_id')
        data_list = []
        for role in query:
            dict = await role.to_dict()
            # 直接使用预加载的对象属性，避免额外查询
            dict["start_x"] = role.x if role.x else None
            dict["start_y"] = role.y if role.y else None
            dict["end_x"] = role.node_to_id.x if role.node_to_id else None
            dict["end_y"] = role.node_to_id.y if role.node_to_id else None
            data_list.append(dict)

        return data_list

AGV_car_controller = AGVcarController()
AGV_position_controller = AGVPositionController()
